import { CodeListItem } from '@ibiz-template/runtime';
import { useNamespace } from '@ibiz-template/vue3-util';
import { isNil } from 'ramda';
import { defineComponent, PropType, ref, watch } from 'vue';
import { IAppCodeList } from '@ibiz/model-core';
import './code-list.scss';

export const IBizCodeList = defineComponent({
  name: 'IBizCodeList',
  props: {
    codeListItems: {
      type: Array<CodeListItem>,
    },
    codeList: {
      type: Object as PropType<IAppCodeList>,
      required: true,
    },
    value: {
      type: [String, Number],
    },
  },
  setup(props) {
    const ns = useNamespace('code-list');
    const items = ref<IData[]>([]);

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          if (isNil(newVal) || newVal === '') {
            // 空值置空
            items.value = [];
          } else {
            // 非空值解析代码表
            let values: string[] | number[];
            if (typeof newVal === 'string') {
              values = newVal.split(',');
            } else {
              values = [newVal];
            }
            items.value = values.map(val => {
              const findItem = props.codeListItems?.find(
                // eslint-disable-next-line eqeqeq
                item => item.value == val,
              );
              return {
                text: findItem?.text || val,
                color: findItem?.color,
              };
            });
          }
        }
      },
      { immediate: true },
    );

    return { items, ns };
  },
  render() {
    return (
      <span class={this.ns.b()}>
        {this.items.length === 0
          ? this.codeList.emptyText
          : this.items.map((item, index) => {
              return [
                index !== 0 ? this.codeList?.textSeparator : null,
                <span
                  class={this.ns.e('item')}
                  style={this.ns.cssVarBlock({
                    'item-color': `${item.color}`,
                  })}
                >
                  {item.text}
                </span>,
              ];
            })}
      </span>
    );
  },
});
